import React, { useState, useEffect } from 'react';
import {
  StyleSheet,
  View,
  Text,
  Dimensions,
  ScrollView,
  TouchableOpacity,
} from 'react-native';
import { LineChart, BarChart } from 'react-native-chart-kit';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { RootStackParamList } from '../types';
import { Ionicons } from '@expo/vector-icons';
import { useTheme } from '../contexts/ThemeContext';

type StatisticsScreenNavigationProp = NativeStackNavigationProp<RootStackParamList>;

interface TimeRecord {
  taskId: string;
  duration: number;
  timestamp: string;
}

interface Task {
  id: string;
  title: string;
  coverImage: string;
}

interface DailyTaskTime {
  [taskId: string]: number;
}

const StatisticsScreen: React.FC = () => {
  const { colors } = useTheme();
  const navigation = useNavigation<StatisticsScreenNavigationProp>();
  const [tasks, setTasks] = useState<Task[]>([]);
  const [selectedTask, setSelectedTask] = useState<string | null>(null);
  const [weeklyData, setWeeklyData] = useState<number[]>([0, 0, 0, 0, 0, 0, 0]);
  const [dailyTaskTimes, setDailyTaskTimes] = useState<DailyTaskTime>({});
  const [totalTime, setTotalTime] = useState(0);
  const [selectedDate, setSelectedDate] = useState(new Date());

  useEffect(() => {
    loadData();

    // 添加焦点监听器
    const unsubscribe = navigation.addListener('focus', () => {
      loadData();
    });

    return unsubscribe;
  }, [navigation]);

  useEffect(() => {
    // 当选中任务变化时重新计算统计数据
    if (selectedTask) {
      loadData();
    }
  }, [selectedTask]);

  const loadData = async () => {
    try {
      // 加载任务列表
      const savedTasksStr = await AsyncStorage.getItem('tasks');
      const savedTasks: Task[] = savedTasksStr ? JSON.parse(savedTasksStr) : [];
      setTasks(savedTasks);

      // 加载时间记录
      const savedRecordsStr = await AsyncStorage.getItem('timeRecords');
      if (savedRecordsStr) {
        const records: TimeRecord[] = JSON.parse(savedRecordsStr);
        calculateStatistics(records, savedTasks);
      }
    } catch (error) {
      console.error('加载数据失败:', error);
    }
  };

  const formatDate = (date: Date) => {
    return date.toISOString().split('T')[0];
  };

  const moveDate = (days: number) => {
    const newDate = new Date(selectedDate);
    newDate.setDate(newDate.getDate() + days);
    setSelectedDate(newDate);
    loadData();
  };

  const calculateStatistics = (records: TimeRecord[], taskList: Task[]) => {
    const selectedDateStr = formatDate(selectedDate);
    
    // 计算选定日期的任务时间（分钟）
    const dayTimes: DailyTaskTime = {};
    records.forEach(record => {
      if (record.date === selectedDateStr && record.minutes >= 1) {
        dayTimes[record.taskId] = (dayTimes[record.taskId] || 0) + record.minutes;
      }
    });
    setDailyTaskTimes(dayTimes);

    // 如果有选中的任务，计算其前后7天的数据
    if (selectedTask) {
      const daysToShow = 8; // 显示8天的数据
      const days = Array.from({ length: daysToShow }, (_, i) => {
        const d = new Date(selectedDate);
        d.setDate(d.getDate() - (daysToShow - 1) + i);
        return formatDate(d);
      });

      const dailyMinutes = days.map(date => {
        return records
          .filter(record => record.date === date && record.taskId === selectedTask && record.minutes >= 1)
          .reduce((sum, record) => sum + record.minutes, 0);
      });

      setWeeklyData(dailyMinutes);
    }

    // 计算总时间（分钟）
    const total = records.reduce((sum, record) => {
      if (record.minutes >= 1) {
        return sum + record.minutes;
      }
      return sum;
    }, 0);
    setTotalTime(total);
  };

  const formatDateDisplay = (date: Date) => {
    return `${date.getMonth() + 1}月${date.getDate()}日`;
  };

  const formatDuration = (minutes: number) => {
    if (minutes < 1) return '0分钟';
    
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    
    const parts = [];
    if (hours > 0) parts.push(`${hours}小时`);
    if (mins > 0 || parts.length === 0) parts.push(`${mins}分钟`);
    
    return parts.join('');
  };

  const getTaskTitle = (taskId: string) => {
    const task = tasks.find(t => t.id === taskId);
    return task ? task.title : '未知任务';
  };

  const chartConfig = {
    backgroundColor: colors.card,
    backgroundGradientFrom: colors.card,
    backgroundGradientTo: colors.card,
    decimalPlaces: 2,
    color: (opacity = 1) => `rgba(0, 122, 255, ${opacity})`,
    style: { borderRadius: 16 },
    propsForDots: {
      r: '6',
      strokeWidth: '2',
      stroke: colors.primary
    },
    propsForLabels: {
      fill: colors.text,
    },
  };

  return (
    <ScrollView style={[styles.container, { backgroundColor: colors.background }]}>
      <View style={[styles.card, { backgroundColor: colors.card }]}>
        <Text style={[styles.cardTitle, { color: colors.text }]}>总计时间</Text>
        <Text style={[styles.totalTime, { color: colors.primary }]}>{formatDuration(totalTime)}</Text>
      </View>

      <View style={[styles.card, { backgroundColor: colors.card }]}>
        <View style={styles.dateSelector}>
          <TouchableOpacity onPress={() => moveDate(-1)} style={styles.dateButton}>
            <Ionicons name="chevron-back" size={24} color={colors.primary} />
          </TouchableOpacity>
          <Text style={[styles.dateText, { color: colors.text }]}>{formatDateDisplay(selectedDate)}</Text>
          <TouchableOpacity onPress={() => moveDate(1)} style={styles.dateButton}>
            <Ionicons name="chevron-forward" size={24} color={colors.primary} />
          </TouchableOpacity>
        </View>

        <Text style={[styles.cardTitle, { color: colors.text }]}>选择任务查看趋势</Text>
        <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.taskList}>
          {tasks.map(task => (
            <TouchableOpacity
              key={task.id}
              style={[
                styles.taskButton,
                { backgroundColor: colors.border },
                selectedTask === task.id && { backgroundColor: colors.primary },
              ]}
              onPress={() => setSelectedTask(task.id)}
            >
              <Text
                style={[
                  styles.taskButtonText,
                  { color: colors.textSecondary },
                  selectedTask === task.id && { color: colors.card },
                ]}
              >
                {task.title}
              </Text>
            </TouchableOpacity>
          ))}
        </ScrollView>

        {selectedTask && (
          <ScrollView horizontal showsHorizontalScrollIndicator={false}>
            <LineChart
              data={{
                labels: Array.from({ length: 8 }, (_, i) => {
                  const d = new Date(selectedDate);
                  d.setDate(d.getDate() - 7 + i);
                  return `${d.getMonth() + 1}/${d.getDate()}`;
                }),
                datasets: [{
                  data: weeklyData.map(minutes => Number((minutes / 60).toFixed(2)))
                }]
              }}
              width={Dimensions.get('window').width * 1.5}
              height={220}
              chartConfig={{
                ...chartConfig,
                labelColor: () => colors.text,
                formatYLabel: (value) => Number(value).toFixed(2),
              }}
              style={styles.chart}
              bezier
              yAxisLabel=""
              yAxisSuffix="小时"
              fromZero={true}
              segments={5}
            />
          </ScrollView>
        )}
      </View>

      <View style={[styles.card, { backgroundColor: colors.card }]}>
        <Text style={[styles.cardTitle, { color: colors.text }]}>当日任务时间分布</Text>
        <ScrollView horizontal showsHorizontalScrollIndicator={false}>
          <BarChart
            data={{
              labels: Object.keys(dailyTaskTimes).map(taskId => getTaskTitle(taskId)),
              datasets: [{
                data: Object.values(dailyTaskTimes).map(minutes => Number((minutes / 60).toFixed(2)))
              }]
            }}
            width={Math.max(Dimensions.get('window').width - 32, Object.keys(dailyTaskTimes).length * 100)}
            height={220}
            chartConfig={{
              ...chartConfig,
              labelColor: () => colors.text,
              formatYLabel: (value) => Number(value).toFixed(2),
            }}
            style={styles.chart}
            verticalLabelRotation={30}
            yAxisLabel=""
            yAxisSuffix="小时"
            fromZero={true}
            segments={5}
          />
        </ScrollView>
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
    padding: 16,
  },
  card: {
    backgroundColor: 'white',
    borderRadius: 12,
    padding: 16,
    marginBottom: 16,
  },
  cardTitle: {
    fontSize: 18,
    fontWeight: '600',
    marginBottom: 12,
  },
  totalTime: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#007AFF',
  },
  taskList: {
    flexDirection: 'row',
    marginBottom: 16,
  },
  taskButton: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 20,
    backgroundColor: '#f0f0f0',
    marginRight: 8,
  },
  selectedTaskButton: {
    backgroundColor: '#007AFF',
  },
  taskButtonText: {
    color: '#666',
    fontSize: 14,
  },
  selectedTaskButtonText: {
    color: 'white',
  },
  chart: {
    marginVertical: 8,
    borderRadius: 16,
  },
  dateSelector: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 16,
  },
  dateButton: {
    padding: 8,
  },
  dateText: {
    fontSize: 18,
    fontWeight: '600',
    marginHorizontal: 16,
  },
});

export default StatisticsScreen; 